package com.example.myblog1_0.service.security;

import com.example.myblog1_0.mapper.UserMapper;
import com.example.myblog1_0.model.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xc
 * @Date: 2018/12/23 9:33
 * @Description:
 **/
@Service
public class CustomerServiceImpl implements UserDetailsService{
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        MyUser findUser = userMapper.findUserInfoByName(s);
        if (findUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = createAuthorities(findUser.getRole());
        return new User(findUser.getUsername(),findUser.getPassword(),simpleGrantedAuthorities);
    }
    /**
        将ROLE_USER转换为USER,并存入List里，因为User需要List作为参数
     */
    private List<SimpleGrantedAuthority> createAuthorities(String roleStr) {
        String[] roles = roleStr.split(",");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (String role : roles) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        return simpleGrantedAuthorities;
    }
}
